// const autojsUtils = require('./modules/autojs-utils');
// m-pesa kes ui
"ui";

const Constant = require("./constant.js");

auto();

device.keepScreenOn();

// 之前保存的钱包
Constant.initMtnAndPin();
// let preWalletNumber = storages.create(Constant.WALLET_NAME).get(Constant.WALLET_NUMBER) || "";
// let preWalletPin = storages.create(Constant.WALLET_NAME).get(Constant.WALLET_PIN) || "";

ui.layout(
    <vertical>
        <text id="sceneName"
            w="*"
            h="auto"
            gravity="center"
            marginTop="16"
            textColor="red"
            textStyle="bold"
            textSize="16"
            text={Constant.WALLET_MPESA_KES_NAME} />

        <input id="wallet"
            marginTop="10"
            hint="请输入钱包号码, 带0开头"
            text={Constant.getMtn()}
            textSize="14" />

        <input id="pin"
            marginTop="10"
            hint="请输入钱包PIN"
            text={Constant.getPin()}
            textSize="14" />

        <input id="amount"
            marginTop="10"
            hint="请输入测试转账金额"
            text={Constant.getAmount()}
            textSize="14" />

        <button id="saveAndStartTransfer"
            marginTop="10"
            text="启动脚本-测试转账" />

        <button id="saveAndStartBills"
            marginTop="10"
            text="启动脚本-查看流水" />

        <button id="saveOnly"
            marginTop="10"
            text="仅保存钱包号" />

    </vertical>
);

ui.saveAndStartTransfer.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();
    var amount = ui.amount.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveAndStartTransfer: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveAndStartTransfer: pin错误!");
        return;
    }

    if (!amount || (amount.length <= 0)) {
        // main();
        toast("saveAndStartTransfer: amount错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);
    Constant.setAmount(amount);

    toast(name + "," + pin + "," + amount + " 已启动脚本-测试转账");

    setTimeout(() => {
        // 启动脚本
        threads.start(function () {
            //在新线程执行的代码
            main(true);
        });
    }, 2000);
});

ui.saveAndStartBills.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();
    var amount = ui.amount.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveAndStartBills: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveAndStartBills: pin错误!");
        return;
    }

    if (!amount || (amount.length <= 0)) {
        // main();
        toast("saveAndStartBills: amount错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);
    Constant.setAmount(amount);

    toast(name + "," + pin + "," + amount + " 已启动脚本-查看流水");

    setTimeout(() => {
        // 启动脚本
        threads.start(function () {
            //在新线程执行的代码
            main(false);
        });
    }, 2000);
});

ui.saveOnly.click(function () {
    var name = ui.wallet.text();
    var pin = ui.pin.text();
    var amount = ui.amount.text();

    if (!name || (name.length <= 8)) {
        // main();
        toast("saveOnly: 钱包号错误!");
        return;
    }

    if (!pin || (pin.length <= 2)) {
        // main();
        toast("saveOnly: pin错误!");
        return;
    }

    if (!amount || (amount.length <= 0)) {
        // main();
        toast("saveOnly: amount错误!");
        return;
    }

    // 保存本地
    Constant.setMtn(name);
    Constant.setPin(pin);
    Constant.setAmount(amount);

    toast(name + "," + pin + "," + amount + " 已保存 saveOnly");
});


const BaseSmsUtil = require("./baseSmsUtil.js");
const BaseApiUrl = require("./baseApiUrl.js");
const BaseHttpUtil = require("./baseHttpUtil.js");

const MpesaKesAppOpen = require("./mpesaKesAppOpen.js");
const MpesaKesPageUtil = require("./mpesaKesPageUtil.js");
const MpesaKesFunAction = require("./mpesaKesFunAction.js");


// 转账信息
let targetTransferAmount = "";
let targetTransferId = "";
let targetTransferAccount = "";
let targetTransferReference = "";

const initMtnTransfer = (data) => {
    targetTransferAmount = data.amount + "";
    targetTransferId = data.id + "";
    targetTransferAccount = data.mtn + "";
    targetTransferReference = data.reference + "";
}

const isValidMtnTransfer = () => {
    let result1 = targetTransferAmount || "";
    let result2 = targetTransferId || "";
    let result3 = targetTransferAccount || "";

    return ((result1.length > 0) && (result2.length > 0) && (result3.length > 0));
}

const cleanMtnTransfer = () => {
    targetTransferAmount = "";
    targetTransferId = "";
    targetTransferAccount = "";
    targetTransferReference = "";
}

const printMtnTransferLog = () => {
    console.log(Constant.UI_SDK_VERSION + "targetTransferAmount: " + targetTransferAmount + ",\ntargetTransferId: " + targetTransferId + ",\ntargetTransferAccount: " + targetTransferAccount + ",\ntargetTransferReference: " + targetTransferReference);
}

/** 启动脚本逻辑 */
function main(isDoTransfer) {
    // 设置坐标宽高
    // setScreenMetrics(720, 1640);
    console.log("w:" + device.width + " ,h:" + device.height);

    // 程序结束自动 隐藏控制台
    console.show(false);
    // --temp close
    if (false) {
        console.setMaxLines(15);
    }

    // 转账信息
    targetTransferAmount = "";
    targetTransferId = "";
    targetTransferAccount = "";
    targetTransferReference = "";

    // 是否需要重启app
    let isNeedRestartWalletApp = false;

    // 是否需要重启脚本
    let isNeedRestartScript = false;

    // 上传短信
    BaseSmsUtil.syncSmsData();

    console.log(Constant.UI_SDK_VERSION + "当前设备: " + Constant.getMtn());
    // sleep(5 * 1000);

    // momo 钱包
    MpesaKesAppOpen.openMpesaApp();

    // 上传短信 
    BaseSmsUtil.syncSmsData();
    sleep(2 * 1000);

    // 测试 --- temp close
    let testTimes = 0;

    while (true) {
        testTimes += 1;
        if (testTimes > 5) {
            console.log("======= 测试结束, 停止脚本");
            return;
        }
        console.log("======== testTimes:" + testTimes);
        sleep(1000);
        // 清空转账信息
        cleanMtnTransfer();

        // 页面状态
        let pageStatus = MpesaKesPageUtil.doCheckPageStatus();
        let isLoginStep1Page = pageStatus.isLoginStep1Page;
        let isLoginStep2Page = pageStatus.isLoginStep2Page;
        let isLoginPinPage = pageStatus.isLoginPinPage;
        let isHomePage = pageStatus.isHomePage;
        let isBillListPage = pageStatus.isBillListPage;
        let isBillDetailPage = pageStatus.isBillDetailPage;
        let isSendMoneyPage = pageStatus.isSendMoneyPage;
        let isSendMoneyMobileSelectPage = pageStatus.isSendMoneyMobileSelectPage;
        let isSendMoneyMobileInputPage = pageStatus.isSendMoneyMobileInputPage;
        let isSendMoneyAmountInputPage = pageStatus.isSendMoneyAmountInputPage;
        let isSendMoneyConfirmPage = pageStatus.isSendMoneyConfirmPage;
        let isSendMoneyConfirmPinInputPage = pageStatus.isSendMoneyConfirmPinInputPage;
        let isSendMoneySuccessPage = pageStatus.isSendMoneySuccessPage;
        let isSendMoneyFailPage = pageStatus.isSendMoneyFailPage;

        // 如果是流水列表页
        if (isBillListPage) {
            // 返回首页
            back();
            sleep(1000);
        }

        // 如果是流水详情页
        if (isBillDetailPage) {
            // 返回首页
            back();
            sleep(1000);
            back();
            sleep(1000);
        }

        // 如果是转账页
        if (isSendMoneyPage) {
            // 返回首页
            click(device.width / 8 * 1, device.height - 40);
            sleep(1000);
        }

        // 如果是转账-mobile select页
        if (isSendMoneyMobileSelectPage) {
            // 返回首页
            back();
            sleep(1000);
            click(device.width / 8 * 1, device.height - 40);
            sleep(1000);
        }

        // 如果是转账-mobile input页
        if (isSendMoneyMobileInputPage) {
            // 返回首页
            back();
            sleep(1000);
            back();
            sleep(1000);
            click(device.width / 8 * 1, device.height - 40);
            sleep(1000);
        }

        // 如果是转账-amount input页
        if (isSendMoneyAmountInputPage) {
            // 返回首页
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
            click(device.width / 8 * 1, device.height - 40);
            sleep(1000);
        }

        // 如果是转账-confirm页
        if (isSendMoneyConfirmPage) {
            // 返回首页
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
            click(device.width / 8 * 1, device.height - 40);
            sleep(1000);
        }

        // 如果是转账-confirm页
        if (isSendMoneyConfirmPinInputPage) {
            // 返回首页
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
            back();
            sleep(1000);
            click(device.width / 8 * 1, device.height - 40);
            sleep(1000);
        }

        // 如果是转账-success页
        if (isSendMoneySuccessPage) {
            // 返回首页
            MpesaKesFunAction.doSendMoneySuccessDone();
        }

        // 如果是转账-fail页
        if (isSendMoneyFailPage) {
            // 返回首页
            MpesaKesFunAction.doSendMoneyFailDone();
        }

        // 上传短信
        BaseSmsUtil.syncSmsData();
        sleep(1 * 1000);

        // 获取脚本状态信息 -- temp close
        if (false) {
            let url = BaseApiUrl.checkOperStatus();
            let checkOperStatusParams = { phone: Constant.getMtn() }
            let checkOperStatusResult = BaseHttpUtil.sendPostSync(url, checkOperStatusParams)
            if (checkOperStatusResult !== null) {
                isNeedRestartWalletApp = checkOperStatusResult.momo || false;
                isNeedRestartScript = checkOperStatusResult.script || false;
            } else {
                isNeedRestartWalletApp = false;
                isNeedRestartScript = false;
            }
        }

        if (isNeedRestartScript) {
            sleep(1 * 1000);
            // 清空控制台
            console.clear();
            continue;
        }

        // 判断是否要重启app
        if (isNeedRestartWalletApp) {
            // 走关闭流程
            MpesaKesAppOpen.closeMpesaApp();

            // 走重启流程
            MpesaKesAppOpen.openMpesaApp();

            // 清空控制台
            console.clear();
            continue;

        } else {
            // 判断是否为登录-手机号页
            if (isLoginStep1Page) {
                // 清空控制台
                // console.clear();

                // 走登录-手机号流程
                let doToLoginStep2Result = MpesaKesFunAction.doToLoginStep2();
                if (doToLoginStep2Result) {
                    // 判断是否为 login step2 page 页
                    isLoginStep2Page = MpesaKesPageUtil.doOpenLoginStep2Page();
                }
            }

            // 判断是否为登录-手机号页
            if (isLoginStep2Page) {
                // 清空控制台
                // console.clear();

                // 走登录-手机号流程
                let doToLoginStepPinResult = MpesaKesFunAction.doToLoginStepPin();
                if (doToLoginStepPinResult) {
                    // 判断是否为 pin 页
                    isLoginPinPage = MpesaKesPageUtil.doOpenLoginPinPage();
                }
            }

            // 判断是否为登录-PIN页
            if (isLoginPinPage) {
                // 清空控制台
                // console.clear();

                // 走登录-PIN流程
                let doPinResult = MpesaKesFunAction.doPinInput();
                if (doPinResult) {
                    // 判断是否为 首页
                    isHomePage = MpesaKesPageUtil.doOpenHomePage();
                }
            }

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                //console.clear();

                // 获取转账信息
                cleanMtnTransfer();
                // -- temp close 放款
                if (false) {
                    let url = BaseApiUrl.getMtnTransferAccount();
                    let mtnAccountParams = { num: "1", phone: Constant.getMtn() }
                    let mtnAccountResult = BaseHttpUtil.sendPostSync(url, mtnAccountParams)
                    if (mtnAccountResult !== null) {
                        if (mtnAccountResult.length > 0) {
                            initMtnTransfer(mtnAccountResult[0]);
                        } else {
                            cleanMtnTransfer();
                        }
                    } else {
                        cleanMtnTransfer();
                    }

                    // 清空控制台
                    console.clear();

                    // 打印转账信息
                    printMtnTransferLog();
                }
                // Test -- temp close 测试放款
                if (isDoTransfer) {
                    console.log("==== 测试放款");
                    initMtnTransfer({
                        id: "id_TEST_T1",
                        amount: Constant.getAmount(),
                        mtn: Constant.TARGET_MPESA_KES_MOBILE,
                        reference: Constant.TARGET_MPESA_KES_REFERENCE
                    });
                    // 打印转账信息
                    printMtnTransferLog();
                }
            }

            // 判断是否需要转账
            if (isValidMtnTransfer()) {
                console.log(Constant.UI_SDK_VERSION + "需要执行转账");
                // 走打开 Send Money 流程
                let doToSendMoneyPageResult = MpesaKesFunAction.doToSendMoneyPage();
                if (doToSendMoneyPageResult) {
                    // 判断是否为 Send Money 页
                    let doOpenSendMoneyPageResult = MpesaKesPageUtil.doOpenSendMoneyPage();
                    if (doOpenSendMoneyPageResult) {
                        // 点击 send money
                        let doToSendMoneyMobileSelectPageResult = MpesaKesFunAction.doToSendMoneyMobileSelectPage();
                        if (doToSendMoneyMobileSelectPageResult) {
                            // 判断是否为选择号码页
                            let doOpenSendMoneyMobileSelectPageResult = MpesaKesPageUtil.doOpenSendMoneyMobileSelectPage();
                            if (doOpenSendMoneyMobileSelectPageResult) {
                                let doToSendMoneyMobileInputPageResult = MpesaKesFunAction.doToSendMoneyMobileInputPage();
                                if (doToSendMoneyMobileInputPageResult) {
                                    // 判断是否为输入号码页
                                    let doOpenSendMoneyMobileInputPageResult = MpesaKesPageUtil.doOpenSendMoneyMobileInputPage();
                                    if (doOpenSendMoneyMobileInputPageResult) {
                                        // 输入钱包号
                                        let doSendMoneyInputTargetAccountResult = MpesaKesFunAction.doSendMoneyInputTargetAccount(targetTransferAccount);
                                        if (doSendMoneyInputTargetAccountResult) {
                                            // 判断是否为 输入金额页
                                            let doOpenSendMoneyAmountInputPageResult = MpesaKesPageUtil.doOpenSendMoneyAmountInputPage();
                                            if (doOpenSendMoneyAmountInputPageResult) {
                                                // 输入金额
                                                let doSendMoneyInputTargetAmountResult = MpesaKesFunAction.doSendMoneyInputTargetAmount(targetTransferAmount);
                                                if (doSendMoneyInputTargetAmountResult) {
                                                    // 判断是否为 转账确认页
                                                    let doOpenSendMoneyConfirmPageResult = MpesaKesPageUtil.doOpenSendMoneyConfirmPage();
                                                    if (doOpenSendMoneyConfirmPageResult) {
                                                        // 点击 确认转账
                                                        let doSendMoneyConfirmResult = MpesaKesFunAction.doSendMoneyConfirm();
                                                        if (doSendMoneyConfirmResult) {
                                                            // 判断是否为 输入密码页
                                                            let doOpenSendMoneyPasswordPageResult = MpesaKesPageUtil.doOpenSendMoneyPasswordPage();
                                                            if (doOpenSendMoneyPasswordPageResult) {
                                                                // 输入密码
                                                                let doSendMoneyInputPasswordResult = MpesaKesFunAction.doSendMoneyInputPassword();
                                                                if (doSendMoneyInputPasswordResult) {
                                                                    let doOpenSendMoneyResultPageResult = MpesaKesPageUtil.doOpenSendMoneyResultPage();
                                                                    if (doOpenSendMoneyResultPageResult.isSuccess) {
                                                                        // 转账成功
                                                                        // ... 上报后台
                                                                        MpesaKesFunAction.doSendMoneySuccessDone();
                                                                    } else {
                                                                        // 转账失败
                                                                        // ... 上报后台
                                                                        MpesaKesFunAction.doSendMoneyFailDone();
                                                                    }
                                                                }
                                                            }
                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }

                        }
                    }
                }
            }

            // 判断是否为 首页
            isHomePage = MpesaKesPageUtil.doOpenHomePage();

            // 判断是否为首页
            if (isHomePage) {
                // 清空控制台
                // console.clear();

                let doClickTransacitonsResult = MpesaKesFunAction.doToBillListPage();
                if (doClickTransacitonsResult) {
                    // 清空控制台
                    // console.clear();

                    // 判断是否为 bill list 页
                    isBillListPage = MpesaKesPageUtil.doOpenBillListPage();
                }
            }

            // 判断是否为 bill list 页
            if (isBillListPage) {
                // 清空控制台
                // console.clear();

                // 获取流程详情
                MpesaKesFunAction.doGetAllBillsForFirstScreen();

                // 清空控制台
                // console.clear();

                // 返回
                back();
                sleep(1 * 1000);

                // 上传短信
                BaseSmsUtil.syncSmsData();

                console.log(Constant.UI_SDK_VERSION + "上报结束, 10秒后重新查询")
                // --- temp close
                if (false) {
                    sleep(10 * 1000);
                }

                // 清空控制台
                // console.clear();

                continue;
            }
            sleep(1 * 1000);

            // 最后都不能匹配成功，
            // 走关闭流程
            MpesaKesAppOpen.closeMpesaApp();

            // 走重启流程
            MpesaKesAppOpen.openMpesaApp();

            // 清空控制台
            console.clear();
        }
    }
}



